package com.zongtui.fourinone.base.config.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.Properties;

public class XmlCallback extends DefaultHandler {
    private boolean textFlag = false;
    private ArrayList propsList;
    private Properties curProps;
    private String curKey;
    private String propsRowDesc;
    private String keyDesc;
    private String curPropsRowDesc;
    private String curKeyDesc;

    public XmlCallback() {
    }

    public void startDocument() throws SAXException {

    }

    public void startElement(String uri, String sName, String qName, Attributes attributes) {
        switch (qName) {
            case "propsTable":
                propsList = new ArrayList();
                break;
            case "propsRow":
                curPropsRowDesc = attributes.getValue("desc");
                curProps = new Properties();
                break;
            default:
                //LogUtil.fine(qName);
                curKeyDesc = attributes.getValue("desc");
                curKey = qName;
                textFlag = true;
                break;
        }
    }

    public void characters(char[] data, int start, int length) {
        String content = new String(data, start, length);
        if (textFlag) {
            //LogUtil.fine(content);
            if (keyDesc == null || (curKeyDesc != null && curKeyDesc.equals(keyDesc)))
                curProps.put(curKey, content.trim());
        }
    }

    public void endElement(String uri, String sName, String qName) {

        if (qName.equals("propsTable")) {
        } else if (qName.equals("propsRow")) {
            if (propsRowDesc == null || (curPropsRowDesc != null && curPropsRowDesc.equals(propsRowDesc)))
                propsList.add(curProps);
        } else {
            textFlag = false;
        }
    }

    public void endDocument() throws SAXException {
        //LogUtil.fine("end parse xml");
    }

    public ArrayList getPropsList() {
        return propsList;
    }

    public void setPropsRowDesc(String propsRowDesc) {
        this.propsRowDesc = propsRowDesc;
    }

    public void setKeyDesc(String keyDesc) {
        this.keyDesc = keyDesc;
    }
}